package javaLanguage.javaMultithread;

import java.util.ArrayList;

public class threadCommunication {
    static final ArrayList<String> persons = new ArrayList<>();

    static class threadProduce extends Thread{
        @Override
        public void run() {
            while (true){
                synchronized (persons){
                    if(persons.get(0).equals("生产")){
                        try {
                            Thread.sleep(3000);
                        } catch (Exception e){
                            e.printStackTrace();
                        }
                        System.out.printf("目前正在%s\n", persons.get(0));
                        persons.remove(0);
                        persons.add("消费");
                        persons.notifyAll();
                    }else{
                        try {
                            persons.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }


            }
        }
    }

    static class threadConsume extends Thread{
        @Override
        public void run() {
            while (true) {
                synchronized (persons) {
                    if (persons.get(0).equals("消费")) {
                        System.out.printf("目前正在%s\n", persons.get(0));
                        persons.remove(0);
                        persons.add("生产");
                        persons.notifyAll();

                    } else {
                        try {
                            persons.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        threadConsume consume = new threadConsume();
        threadProduce produce = new threadProduce();

        persons.add("生产");

        produce.start();
        consume.start();

    }
}
